package com.dtagri.fjwlw.ui.tdvideo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.android.nvssdklib.NvssdkAPI;
import com.android.nvssdklib.RECT;
import com.dtagri.fjwlw.bean.tdvideo.cls_Channel;
import com.dtagri.fjwlw.bean.tdvideo.cls_Host;
import com.dtagri.fjwlw.fragment.VideoCenterFragment;
import com.dtagri.fjwlw.ui.Show_Download_View;
import com.dtagri.fjwlw.ui.VView;
import com.dtagri.fjwlw.util.TDVideoHelper;













import android.content.Context;
import android.graphics.Point;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/**
 * 【天地伟业】
 * 
 * @author Administrator
 * 
 */
public class CLS_VideoViewController {

	/** 当前界面中界面大小 */
	class cls_ViewSize {
		public int m_iFullWidth;
		public int m_iFullHeight;
		public int m_iBodyHeight;
		public int m_iNormalWidth;
		public int m_iNormalHeight;
	}

	private cls_ViewSize m_clsViewSize = new cls_ViewSize();
	/** 云台控制速度 */
	private int m_iPTZSpeed;

	/** 用保存主机ID（m_iHostID）和这个主机的LogonID对应 */
	public Map<String, String> m_mapstrHostIDToLogID = new HashMap<String, String>();

	/** 创建CLS_Channel的数组（16设置成宏定义），与输出的UIView相对应 */
	private CLS_Channel[] m_CLSChannel;
	// 每个View对应的登录ID
	private int[] m_ChannelID;
	/** 每个View对应的视频播放状态 */
	private int[] m_iViewState;
	/** 当前选中的View */
	private int m_iSelectedView;
	private int m_iPreSelectView;

	/** 当前选中View的大小 */
	private RECT m_Rect;
	public cls_Channel m_cls_Channel;

//	private static Show_Video_View m_ReturnNotes;
	private static TDVideoHelper helper;
	private static Show_Download_View m_PlayBackNotes;
	private String m_strSelectedDeviceName;
	private String m_strSelectedChannelName;
	public static int m_iProDeviceID = -1;
	public static int m_iProChannelID = -1;

	private String m_strGPSInfo;
	private boolean m_blSingleLogon;

	public static CLS_VideoViewController instance = null;

	public static CLS_VideoViewController GetInstance() {
		if (instance == null) {
			instance = new CLS_VideoViewController();
		}
		return instance;
	}

	public String getStrGPSInfo() {
		return m_strGPSInfo;
	}

	public void setStrGPSInfo(String strGPSInfo) {
		this.m_strGPSInfo = strGPSInfo;
	}

	// CLS_VideoViewController类的构造函数
	public CLS_VideoViewController() {
		m_ChannelID = new int[4];
		m_iViewState = new int[4];
		m_CLSChannel = new CLS_Channel[4];
		m_Rect = new RECT();
		m_Rect.bottom = 0;
		m_Rect.left = 0;
		m_Rect.right = 0;
		m_Rect.top = 0;
		for (int i = 0; i < 4; i++) {
			m_ChannelID[i] = -1;
			m_iViewState[i] = -1;
			m_CLSChannel[i] = new CLS_Channel();
		}

		m_iSelectedView = 0;
		m_iPreSelectView = 0;
		m_blSingleLogon = false;

	}

//	public void Registe(Show_Video_View _TempObject) {
//		m_ReturnNotes = _TempObject;
//	}
	public void Registe(TDVideoHelper _TempObject) {
		helper = _TempObject;
		System.out.println("测试注册----------------------");
	}

	public void Registe(Show_Download_View _TempObject) {
		m_PlayBackNotes = _TempObject;
	}

//	public void UnRegiste(Show_Video_View _TempObject) {
//		m_ReturnNotes = null;
//	}
	public void UnRegiste(TDVideoHelper _TempObject) {
		helper = null;
	}
	public void UnRegiste(Show_Download_View _TempObject) {
		m_PlayBackNotes = null;
	}

	private void SendMsgToActivity(Message message) {
		if (helper != null) {
			helper.msgHandler.sendMessage(message);
		}
		if (m_PlayBackNotes != null) {
			m_PlayBackNotes.messageHandler.sendMessage(message);
		}
	}

	public boolean HasSelectVideo() {
		if (m_ChannelID[m_iSelectedView] == -1)
			return false;
		return true;
	}

	public boolean HasPlayed() {
		if (m_iViewState[m_iSelectedView] == 1)
			return true;
		return false;
	}

	public boolean HasRev() {
		if (m_iViewState[m_iSelectedView] == 0)
			return true;
		return false;
	}

	/** 获得当前选定窗口的登录ID */
	public int GetSelectChannelLogonID() {
		return m_CLSChannel[m_iSelectedView].GetLogonID();
	}

	// 获得当前播放视频的主机名称
	public String GetSelectHostName() {
		return m_strSelectedDeviceName;
	}

	public String GetSelectChannelName() {
		return m_strSelectedChannelName;
	}

	// 设置云台移动速度
	public boolean SetPTZSpeed(int _iSpeed) {
		m_iPTZSpeed = _iSpeed;
		m_CLSChannel[m_iSelectedView].SetPTZSpeed(_iSpeed);
		return true;
	}

	// 获得当前通道云台移动速度
	public int GetPtzSpeed() {
		return m_iPTZSpeed;
	}

	/** 播放选中通道视频 */
	public boolean LogonSelctedChannel(cls_Host _clsSelectHost,
			cls_Channel _clsSelectChannel, VView _viewObject) {
		cls_Channel SelectChannel = _clsSelectChannel;
		cls_Host SelectHost = _clsSelectHost;
		m_strSelectedDeviceName = SelectHost.getHostName();
		m_strSelectedChannelName = SelectChannel.getChannelName();
		m_CLSChannel[m_iSelectedView].SetChannelEntity(SelectChannel);
		m_CLSChannel[m_iSelectedView].SetHostEntity(SelectHost);
		// 设置当前窗口对应的通道ID
		m_ChannelID[m_iSelectedView] = SelectChannel.getChannelID();
		// 设置当前播放视频流类型
		m_CLSChannel[m_iSelectedView].SetStreamNO(SelectChannel.getStreamNo());
		// 设置控制步长
		m_CLSChannel[m_iSelectedView].SetPTZSpeed(SelectChannel
				.getControlStep());
		// 设置播放通道序号
		m_CLSChannel[m_iSelectedView].SetChannelNum(SelectChannel
				.getChannelNo() - 1);
		// 设置云台控制协议
		m_CLSChannel[m_iSelectedView].SetPTZController(SelectChannel
				.getProtocol() + ",n,8,1");
		// 设置设备地址
		m_CLSChannel[m_iSelectedView].SetDeviceAddress();
		m_CLSChannel[m_iSelectedView].SetServerIP(SelectHost.getConnectIP());
		m_CLSChannel[m_iSelectedView].m_viewObject = _viewObject;
		String hostID = SelectHost.getHostID() + "";

		// 每次登录前退陆其他的设备 add by cpx 110305
		LogoffOtherHost(SelectHost.getHostID());
		// end add

		// 应该传入播放控件的位置和大小，此处未加
		int iLogonID = m_CLSChannel[m_iSelectedView].Logon();
		if (iLogonID >= 0) {
			m_mapstrHostIDToLogID.put(SelectHost.getHostID() + "", iLogonID
					+ "");
			m_iViewState[m_iSelectedView] = 0;
			Message message1 = Message.obtain();
			message1.arg1 = 0; // 登录成功
			helper.msgHandler.sendMessage(message1);
		} else {
			Message message = Message.obtain();
			message.arg1 = -1; // 登录失败
			helper.msgHandler.sendMessage(message);
		}
		return true;
	}

	/** 播放选中通道视频 */
	public boolean PlaySelctedChannel() {
		if (HasPlayed()) {
			return true;
		}
		if (!m_CLSChannel[m_iSelectedView].StartPlay(m_iSelectedView)) {
			Message message = Message.obtain();
			message.arg1 = -2; // 播放接受数据失败
			helper.msgHandler.sendMessage(message);
			return false;
		} else {
			m_iViewState[m_iSelectedView] = 0;
			Message message1 = Message.obtain();
			message1.arg1 = 1; // 开始播放接受数据
			helper.msgHandler.sendMessage(message1);
			return true;
		}
	}

	// 设置选中View序号
	public boolean SetSelectedView(int _iSelectedView) {
		m_iPreSelectView = m_iSelectedView;
		m_iSelectedView = _iSelectedView;
		return true;
	}

	// 获得选中View序号
	public int GetSelectedView() {
		return m_iSelectedView;
	}

	/**
	 * 获得当前窗口对应的CLS_Channel对象
	 */
	public CLS_Channel GetCurrentCLS_Channel() {
		if (m_ChannelID[m_iSelectedView] < 0)
			return null;
		return m_CLSChannel[m_iSelectedView];
	}

	/**
	 * 设置预置位变量
	 * */
	public boolean SetPresetPara(int _iPreset) {

		m_CLSChannel[m_iSelectedView].setM_iPreset(_iPreset); // 设备地址

		return true;
	}

	/**
	 * 云台控制
	 * 
	 * @param _iDirection
	 */
	public boolean ControlPTZ(int _iActionType) {

		return m_CLSChannel[m_iSelectedView].PTZControl(_iActionType);
	}

	/**
	 * 3D定位
	 */

	public boolean Device3DCtrl(int _iNewCenterX, int _iNewCenterY,
			int _iFullWidth, int _iFullHeight, int _iOrientation) {
		int L = 0, R = 0, U = 0, D = 0, W = 0, T = 0, ox = 0, oy = 0;
		int iTempAddress = m_CLSChannel[m_iSelectedView].GetDeviceAddress();

		// if (1 == _iOrientation)
		// {
		// ox = _iNewCenterX;
		// oy = _iNewCenterY;
		// }
		// else
		{
			// ox = _iFullWidth-_iNewCenterX;
			// oy = _iFullHeight-_iNewCenterY;
			ox = _iNewCenterX;
			oy = _iNewCenterY;
			if (1 == _iOrientation) {
				T = 1;
				W = 0;
			} else {
				T = 0;
				W = 1;
			}
		}

		if (ox < _iFullWidth / 2) {
			L = 1;
			R = 0;
		} else {
			L = 0;
			R = 1;
		}

		if (oy < _iFullHeight / 2) {
			U = 1;
			D = 0;
		} else {
			U = 0;
			D = 1;
		}

		int[] DecBuf = new int[9];
		DecBuf[0] = 0xf6;
		DecBuf[1] = 8;
		DecBuf[2] = iTempAddress/* (*m_itCurObs)->m_iDevAddr */;
		DecBuf[3] = 0x52;
		DecBuf[4] = (R + L * 2 + U * 4 + D * 8 + W * 16 + T * 32);
		DecBuf[5] = (int) (Math.abs(ox - _iFullWidth / 2) * 63 / (_iFullWidth / 2));
		DecBuf[6] = (int) (Math.abs(oy - _iFullHeight / 2) * 63 / (_iFullHeight / 2));
		DecBuf[7] = (int) (_iFullWidth * 15 / _iFullWidth);
		DecBuf[8] = ((DecBuf[1] + DecBuf[2] + DecBuf[3] + DecBuf[4] + DecBuf[5]
				+ DecBuf[6] + DecBuf[7]) & 0x7f);
		int iTempComPort = m_CLSChannel[m_iSelectedView].GetChannelEntity()
				.getComNumber();
		if (m_CLSChannel[m_iSelectedView].PTZ3DControl(DecBuf, 9, iTempComPort))
			return true;
		else
			return false;
	}

	/**
	 * 
	 * 图像本地抓拍响应函数
	 */
	public boolean GetCapture() {
		if (m_CLSChannel[m_iSelectedView].CapturePicture())
			return true;
		return false;
	}

	/**
	 * 
	 * 图像前端抓拍响应函数
	 */
	public boolean GetSnapshotCapture() {
		if (m_CLSChannel[m_iSelectedView].SnapshotCapturePicture())
			return true;
		return false;
	}

	public cls_Channel GetSelectedChannel() {
		return null;
	}

	/**
	 * 判断当前选择的主机是否在线
	 */
	public boolean IsCurrentHostLogOn() {
		return false;
	}

	/**
	 * 预置位
	 * 
	 * @param _iType
	 * @param _iValue
	 */
	public int OnPreset(int _iType, int _iValue) {
		return 0;
	}

	/** 停止视频播放 */
	public boolean StopVideo() {
		if (m_CLSChannel[m_iSelectedView].StopPlay()) {
			m_ChannelID[m_iSelectedView] = -1;
			// m_iViewState[m_iSelectedView] = -1;
		}

		return true;
	}

	public boolean Test() {
		if (m_CLSChannel[m_iSelectedView].Test() == 0)
			return true;
		return false;
	}

	public boolean Set3GDialogStart() {
		if (m_CLSChannel[m_iSelectedView].Set3GDialogStart() == 0)
			return true;
		return false;
	}

	public boolean Set3GDialogStop() {
		if (m_CLSChannel[m_iSelectedView].Set3GDialogStop() == 0)
			return true;
		return false;
	}

	/** 退陆 */
	public boolean Logoff() {
		StopVideo();
		if (m_CLSChannel[m_iSelectedView].GetLogonID() >= 0) {
			m_CLSChannel[m_iSelectedView].LogOff();
			m_mapstrHostIDToLogID.put(m_CLSChannel[m_iSelectedView]
					.GetChannelEntity().getHostID() + "", "-1");
			m_CLSChannel[m_iSelectedView].SetLogonID(-1);
			m_iViewState[m_iSelectedView] = -1;
		}
		return true;
	}

	// 退陆其他已登录设备
	public boolean LogoffOtherHost(int _iHostID) {
		String strTemp = "";
		int iLogID = -1;
		Iterator iter = m_mapstrHostIDToLogID.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) iter
					.next();
			strTemp = entry.getKey();
			if (Integer.parseInt(strTemp) != _iHostID) {
				strTemp = entry.getValue();
				iLogID = Integer.parseInt(strTemp);
				if (iLogID >= 0) {
					NvssdkAPI.GetInstance().NetClient_Logoff(iLogID);
					entry.setValue("-1");
					try {
						Thread.sleep(100, 0);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return true;
	}

	/** 当前界面中界面大小 */
	public void SetViewSize(int _iFullWidth, int _iFullHeight,
			int _iBodyHeight, int _iNormalWidth, int _iNormalHeight) {
		m_clsViewSize.m_iFullWidth = _iFullWidth;
		m_clsViewSize.m_iFullHeight = _iFullHeight;
		m_clsViewSize.m_iBodyHeight = _iBodyHeight;
		m_clsViewSize.m_iNormalWidth = _iNormalWidth;
		m_clsViewSize.m_iNormalHeight = _iNormalHeight;
	}

	public boolean LogoffHost(int _iHostID) {
		String strTemp = "";
		int iLogID = -1;
		Iterator iter = m_mapstrHostIDToLogID.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) iter
					.next();
			strTemp = entry.getKey();
			if (Integer.parseInt(strTemp) == _iHostID) {
				strTemp = entry.getValue();
				iLogID = Integer.parseInt(strTemp);
				if (iLogID >= 0) {
					NvssdkAPI.GetInstance().NetClient_Logoff(iLogID);
					entry.setValue("-1");
					try {
						Thread.sleep(100, 0);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				break;
			}
		}

		m_blSingleLogon = false;
		return true;
	}

	// 回调函数
	public void NetClientMainNotify(int _iLogonID, int _iWparam, int _iLParam) {
		if (_iWparam == 7 && _iLParam == 0) // 登录成功通知
		{
			if ((!m_CLSChannel[m_iSelectedView].IsTurnMode())
					&& (_iLogonID != m_CLSChannel[m_iSelectedView].GetLogonID()))// 是主动模式时不能这么判断
			{
				return;
			} else {
				m_CLSChannel[m_iSelectedView].SetLogonID(_iLogonID);
			}

			if (HasPlayed()) {
				// 接受数据成功
				int[] iWidth = new int[1], iHeight = new int[1];
				NvssdkAPI.GetInstance().NetClient_GetVideoSize(
						_iLogonID,
						m_CLSChannel[m_iSelectedView].GetChannelNum(),
						iWidth,
						iHeight,
						m_CLSChannel[m_iSelectedView].GetChannelEntity()
								.getStreamNo());
				m_CLSChannel[m_iSelectedView].m_viewObject.SetRealVideoSize(
						iWidth[0], iHeight[0]);
				if (NvssdkAPI.GetInstance().SetHandle(0,
						m_CLSChannel[m_iSelectedView].GetulID(),
						m_CLSChannel[m_iSelectedView].m_viewObject,
						m_CLSChannel[m_iSelectedView].m_viewObject.mPixel) == 1) {
				}
			} else {
				m_iViewState[m_iSelectedView] = 0;
				Message message1 = Message.obtain();
				message1.arg1 = 0; // 登录成功
				helper.msgHandler.sendMessage(message1);
			}

		}
		if (_iWparam == 2 && _iLParam == 0) // 重启
		{
			if (_iLogonID != m_CLSChannel[m_iSelectedView].GetLogonID())
				return;
			m_CLSChannel[m_iSelectedView].ServerReset();
			m_iViewState[m_iSelectedView] = 0;

		}
		if (_iWparam == 3) // 表明达到最大连接数
		{

		}
		if (_iWparam == 7 && _iLParam == 1)//
		{

		}
		if (_iWparam == 7 && _iLParam == 4)// 登录失败
		{
			if (_iLogonID != m_CLSChannel[m_iSelectedView].GetLogonID())
				return;
			m_CLSChannel[m_iSelectedView].SetLogonID(-1); // add by cpx 110305
															// 登录失败时 LogonID将被重置
			Message message = Message.obtain();
			message.arg1 = -1; // 登录失败
		}
		if (_iWparam == 7 && _iLParam == 5)// 登录超时
		{
			if (_iLogonID != m_CLSChannel[m_iSelectedView].GetLogonID())
				return;
			m_CLSChannel[m_iSelectedView].SetLogonID(-1); // add by cpx 110305
															// 登录失败时 LogonID将被重置
			Message message = Message.obtain();
			message.arg1 = -3; // 登录失败
			helper.msgHandler.sendMessage(message);
		}
		if (_iWparam == 8)// 接收到视频头
		{
			int[] iWidth = new int[1], iHeight = new int[1];

			if (_iLogonID != m_CLSChannel[m_iSelectedView].GetLogonID())
				return;

			if (HasPlayed()) {
				// add by cpx 110306 修改视频不能正确播放的问题

				// 如果视频大小改变了才重连视频
				NvssdkAPI.GetInstance().NetClient_GetVideoSize(
						_iLogonID,
						m_CLSChannel[m_iSelectedView].GetChannelNum(),
						iWidth,
						iHeight,
						m_CLSChannel[m_iSelectedView].GetChannelEntity()
								.getStreamNo());
				if (m_CLSChannel[m_iSelectedView].m_viewObject
						.IsEqualVideoSize(iWidth[0], iHeight[0])) {
					return;
				}

				if (m_CLSChannel[m_iSelectedView].StopPlay()) {
					m_iViewState[m_iSelectedView] = -1;
				}

				try {
					Thread.sleep(100, 0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				if (!m_CLSChannel[m_iSelectedView].StartPlay(m_iSelectedView)) {
					m_iViewState[m_iSelectedView] = -1;
					Message message = Message.obtain();
					message.arg1 = -2; // 通道号错误，接受数据失败
					helper.msgHandler.sendMessage(message);
				} else {
					m_iViewState[m_iSelectedView] = 0;
					Message message1 = Message.obtain();
					message1.arg1 = 0; // 登录成功，开始接受数据
					helper.msgHandler.sendMessage(message1);
				}
				// end add
				return;
			}
			// 接受数据成功

			NvssdkAPI.GetInstance().NetClient_GetVideoSize(
					_iLogonID,
					m_CLSChannel[m_iSelectedView].GetChannelNum(),
					iWidth,
					iHeight,
					m_CLSChannel[m_iSelectedView].GetChannelEntity()
							.getStreamNo());
			m_CLSChannel[m_iSelectedView].m_viewObject.SetRealVideoSize(
					iWidth[0], iHeight[0]);
			if (NvssdkAPI.GetInstance().SetHandle(0,
					m_CLSChannel[m_iSelectedView].GetulID(),
					m_CLSChannel[m_iSelectedView].m_viewObject,
					m_CLSChannel[m_iSelectedView].m_viewObject.mPixel) == 1) {
				if (NvssdkAPI.GetInstance().NetClient_StartPlay(
						m_CLSChannel[m_iSelectedView].GetulID(),
						m_iSelectedView, m_Rect, 0) != 0) {
				} else {
					m_iViewState[m_iSelectedView] = 1;
				}
			}
			Message message = Message.obtain();
			message.arg1 = 1; // 接受成功，开始播放
			helper.msgHandler.sendMessage(message);
		}

		if (_iWparam == 18)// Query finished record files
		{
			Message message = Message.obtain();
			message.arg1 = 18;
			m_PlayBackNotes.messageHandler.sendMessage(message);
		}

		if (_iWparam == 19)// Download finished
		{
			Message message = Message.obtain();
			message.arg1 = 19;
			message.arg2 = _iLParam;
			m_PlayBackNotes.messageHandler.sendMessage(message);
		}
		if (_iWparam == 20)// Download fault
		{
			Message message = Message.obtain();
			message.arg1 = 20;
			message.arg2 = _iLParam;
			m_PlayBackNotes.messageHandler.sendMessage(message);
		}
		if (_iWparam == 20)// Download fault
		{
			Message message = Message.obtain();
			message.arg1 = 20;
			message.arg2 = _iLParam;
			m_PlayBackNotes.messageHandler.sendMessage(message);
		}
	}

	public void NetClientProxyNotify(int _ulLogonID, int _iCmdKey,
			String _strData, int _iLen) {

	}

	public void NetClientAlarmNotify(int _ulLogonID, int _iChan,
			int _iAlarmState, int _iAlarmType) {

	}

	public void NetClientParamChangeNotify(int _ulLogonID, int _iChan,
			int _itype, int[] _iAlarmType) {

	}

	public void NetClientComRecvNotify(int _ulLogonID, int _iComNo,
			double _dLon, double _dLat, double _dSpeed, String _strTimeCur) {
		setStrGPSInfo("Lon:" + _dLon + ",Lat:" + _dLat + ",Speed:" + _dSpeed
				+ "km/h" + ",Time:" + _strTimeCur);
		Message message = Message.obtain();
		message.arg1 = 2; // 接受GPS显示
		helper.msgHandler.sendMessage(message);
	}

}